import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '../store'
import errorCode from '@/const/errorCode'
import Router from '@/router'


// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000 // 请求超时时间
})

export function axiosRequest(url, info, method, params, config) {
  if (!method) {
    method = 'GET'
  }
  var data = {}
  if (method === 'POST' && params) {
    data = JSON.parse(JSON.stringify(params))
    params = null
  }
  if (method === 'PUT' && params) {
    data = JSON.parse(JSON.stringify(params))
    params = null
  }
  if (!config) {
    config = {}
  }
  var cfg = Object.assign({}, { method: method, url: url, params: params, data: data }, config)
  return service(cfg).then(function(response) {
    return response
  })
}
// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers.common['Authorization'] = 'Bearer ' + store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  const headers = config.headers
  if (headers['content-type'] === 'application/octet-stream;charset=utf-8') {
    return config.data
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})  

// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code && response.data.code !== 0) {
      //refresh_token超时
      if(response.data.code && response.data.code === -2) {
        Message({
          message: response.data.message + '，请重新登录',
          type: 'error'
        })
      } else if (response.data.code && response.data.code === -3) {
        MessageBox.alert('会话超时，请重新登录', '提示', {
          confirmButtonText: '跳转登录页面',
          callback: action => {
            store.dispatch('FedLogOut', {}).then(() => {
              location.reload()// In order to re-instantiate the vue-router object to avoid bugs
            })
          }
        })
      } else if (response.data.code && response.data.code === -1) {
        Message({
          message: response.data.message,
          type: 'error'
        })
      } else {
        if (response.data.message) {
          Message({
            message: response.data.message,
            type: 'error'
          })
        } else {
          Message({
            message: '请求网络错误',
            type: 'error'
          })
        }
      }
      return Promise.reject(response.data)
    }
    return response.data 
  },
  error => {
    const errMsg = error.toString()
    const code = errMsg.substr(errMsg.indexOf('code') + 5)
    //access_token超时
    if(code == '401' && error.response.data.error === "invalid_token"){
      store.dispatch('RefreshToken', {})

      return null;
    } else if (code == '478') {
      Message({  
        message: '验证码错误,请重新输入',
        type: 'error'
      })
    }else if (code == '404'){
      // Router.push({path: '/401'})

    } else {
      Message({  
        message: errorCode[code] || errorCode['default'],
        type: 'error'
      })
    }
    return Promise.reject(error)
  }
)
export default service
